package com.yufei.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import com.yufei.dataretriver.DataRetrieverFactory;
import com.yufei.dataretriver.DataRetrieverFeatures;
import com.yufei.dataretriver.HttpDataRetriever;
import com.yufei.entity.PaginationRule;
import com.yufei.entity.ProxyServer;
import com.yufei.entity.UrlParameter;



/**
 * @author zhao-0244@qq.com to do some common function so they should be static
 *         methods is thread safe and common used
 */
public class CommonUtil{
	public static final String encodingPattern="charset=(.*?)\"";
	static Log mLog = LogFactory.getLog(CommonUtil.class);

	// 扩展词典新增词元
	public synchronized static void addExtTerm(String term) {

	}

	public static void setPropertyForEntity(Object entity, Object value,
			String propertyName) {

		try {
			//
			BeanUtils.setProperty(entity, propertyName, value);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			mLog.info("对属性:"+propertyName+"设置值:"+value+"出错!");
		}
	}



public static String generateXmlStrForObject(Object obj, Class cla) {
		
		Writer outputWriter = new StringWriter(); 

		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(cla);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(obj, outputWriter);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return outputWriter.toString();

	}
	public static boolean isMediaType(String fieldName) {
		/*
		 * if(obj instanceof Collection){ return true; } else{ return false; }
		 */
		if (fieldName.endsWith("Media")) {
			return true;

		} else
			return false;

	}

	public static String getStringFromFile(File file) {
		String str = null;

		byte[] bytes;

		if (file != null) {
			try {
				bytes = IOUtils
						.translantStreamToByte(new FileInputStream(file));
				str = IOUtils.translantByteStreamToString(bytes, "utf-8");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				mLog.debug(file.getAbsoluteFile() + ": not found!");

			} catch (Exception e) {
				// TODO Auto-generated catch block
				mLog.debug(e.getMessage());
			}
		}

		return str;

	}

	// 获取此类以及子类的所有方法
	public static Method getMethod(Class obj, String methodName) {
		Method[] methods = obj.getMethods();
		for (Method method1 : methods) {
			if (method1.getName().equals(methodName)) {

				return method1;

			}
		}
		return null;
	}

	public static String getBaseUrl(String urlStr) {
		urlStr = CommonUtil.formatUrl(urlStr);
		String baseUrl = null;
		if (urlStr.startsWith("http")) {
			if (urlStr.contains("?")) {
				baseUrl = urlStr.substring(0, urlStr.indexOf("?"));
			}

		}
		return baseUrl;

	}

	public static int getCharNumber(char ch, String sourceString) {
		int charNumber = 0;
		char[] charArray = sourceString.toCharArray();
		for (char ch1 : charArray) {
			if (ch1 == ch) {
				charNumber++;
			}
		}
		return charNumber;

	}

	// 替换制定位置的某个字符
	public static String replaceByIndex(String sourceStr, String targetString,
			String[] values) {
		StringBuffer stringBuffer = new StringBuffer();
		String[] strs = sourceStr.split(targetString);
		int position = 0;
		for (String str : strs) {
			if (position < values.length) {
				stringBuffer.append(str).append(values[position]);
			} else {
				stringBuffer.append(str);
			}
			position += 1;
		}

		return stringBuffer.toString();
	}

	// 截取某个特定的字符串更具某个字符出现的位置
	/**
	 * @param ch
	 *            :截取子字符串要参考的字符
	 * @param position
	 *            ：字符第几次出现
	 * @param sourceString
	 * @return 目标字符串中的以零开始，position表示的位置的子字符串
	 */
	public static String subString(char ch, int position, String sourceString) {
		StringBuffer buffer = new StringBuffer();
		int tempPosition = 0;
		char[] chars = sourceString.toCharArray();
		for (char ch1 : chars) {
			if (tempPosition == position) {
				break;
			}
			buffer.append(ch1);
			if (ch1 == ch) {
				tempPosition++;
			}
		}
		return buffer.toString();
	}

	/**
	 * @param url
	 *            ：需要处理的url
	 * @param upUrl
	 *            :需要处理的url所在html页面的链接地址
	 * @return：经过处理过的完整的url
	 */
	public static String normalizeUrl(String url, String upUrl) {
		url = CommonUtil.formatUrl(url);
		upUrl = CommonUtil.formatUrl(upUrl);

		String returnUrl = null;
		if (url.startsWith("http")) {
			returnUrl = url;
			return returnUrl;

		} else {
			
			if (url.startsWith("/") || url.startsWith("../")) {
				url = url.replace("../", "");
				url = url.replaceFirst("/", "");
				
				returnUrl = CommonUtil.subString('/', 3, upUrl) + url;
			}
			

				/*else {
				
					if (CommonUtil.getCharNumber('/', upUrl) <= 3) {
						if (upUrl.contains("?")) {
							returnUrl = upUrl.substring(0, upUrl.lastIndexOf('?'))
									+ url;

						} else {
							if (CommonUtil.getCharNumber('/', upUrl) < 3) {

								returnUrl = upUrl + "/" + url;

							} else {
								returnUrl = upUrl + url;
							}
						}

					}
				}
*/


			

		}//

		return returnUrl;

	}

	/**
	 * @param url
	 * @return
	 * 出去一些不必要的特殊字符,比如：#字符之后的内容
	 */
	public static String formatUrl(String url) {
		String[] filterdStrs = { "amp;", " " };
		for (String str : filterdStrs) {
			url = url.replace(str, "");
		}
		if(url.contains("#")){
			url=url.substring(0, url.indexOf("#"));
		}
		return url;

	}
    @Deprecated
	public static String getHtmlContent(String url, boolean isRequireJS) throws IOException {
		String htmlStr = null;
		ProxyServer proxy=null;
		HttpDataRetriever dataRetriever = DataRetrieverFactory
				.createDataRetriever(new DataRetrieverFeatures(isRequireJS, proxy));
		dataRetriever.setUrl(new URL(url));
		dataRetriever.connect();
		htmlStr =  dataRetriever.getHtmlContent();
		dataRetriever.disconnect();

		return htmlStr;

	}
	public static void main(String[] args){
		/* try {
				String str1=CommonUtil.getHtmlContent("http://list.tmall.com//search_product.htm?q=%B1%CA%BC%C7%B1%BE&type=p&style=&cat=all", false,1000*10,200);
				System.out.print(str1);
				}
		 catch(Exception e){
			 System.out.print(e.getMessage());
			 
		 }
		 String str="ASUS 华硕";
		 String str1="神舟优雅";
		List<Integer>[] vectorofString = CommonUtil.getVectorofString(
				str, str1);
		double similartity = CommonUtil.calculateSimilartityByInteger(vectorofString[0],
				vectorofString[1]);
		System.out.print(similartity);*/
		/*String paginationTemplate="http://www.amazon.cn/s/ref=sr_pg_2?rh=n%3A42692071&page={}&ie=UTF8&qid=1365667401";
		List<String> urls=CommonUtil.makeUrlsByPaginationTemplate(paginationTemplate,0, 100, 3);
		for(String s:urls){
			System.out.print(s+"\n");
		}*/
		int[] ints={123,45,890,1209};
		quickSort1(ints, 0, ints.length-1);
		for(int i:ints){
			System.out.print(" "+i+" ");
		}
		
	}

	/**
	 * @param url
	 * @param isRequireJS
	 * @param requestTimeOut：毫秒 0表示没有限制，表示无限长的时间可以超时
	 * @param connectIntervalTime:秒
	 * @return
	 * @throws IOException
	 */
	@Deprecated
	public static String getHtmlContent(String url, boolean isRequireJS,int requestTimeOut,long connectIntervalTime) throws IOException {
		String htmlStr = null;
		ProxyServer proxy=null;
		DataRetrieverFeatures dataRetrieverFeatures = new DataRetrieverFeatures(isRequireJS, proxy);
		HttpDataRetriever dataRetriever = DataRetrieverFactory
				.createDataRetriever(dataRetrieverFeatures);
		dataRetrieverFeatures.setRequestTimeout(requestTimeOut);
		dataRetrieverFeatures.setConnectIntervalTime(connectIntervalTime);
		
		dataRetriever.setUrl(new URL(url));
		dataRetriever.connect();
		htmlStr =  dataRetriever.getHtmlContent();
		dataRetriever.disconnect();

		return htmlStr;

	}
    @Deprecated
	public static String getHtmlContent(ProxyServer proxyIdentity, boolean isRequestJs, String url)
			throws IOException {
	
        if(CommonUtil.isEmptyOrNull(url)){
        	throw new IllegalArgumentException("url 不能为空后者null!");
        }
		String htmlStr = null;
		HttpDataRetriever dataRetriever = DataRetrieverFactory
				.createDataRetriever(new DataRetrieverFeatures(isRequestJs, proxyIdentity));
	
		dataRetriever.setUrl(new URL(url));
		dataRetriever.connect();
		htmlStr =dataRetriever.getHtmlContent();
		dataRetriever.disconnect();

		return htmlStr;

	}


	public static String upFirstChar(String str) {

		char temp = str.charAt(0);
		temp = Character.toUpperCase(temp);
		str = str.replaceFirst(String.valueOf(str.charAt(0)),
				String.valueOf(temp));
		return str;

	}

	public static String downFirstChar(String str) {

		char temp = str.charAt(0);
		temp = Character.toLowerCase(temp);
		str = str.replaceFirst(String.valueOf(str.charAt(0)),
				String.valueOf(temp));
		return str;

	}

	public static String cleanHtml(String about) {
		// TODO Auto-generated method stub
		// 禁止取出换行，制表符以及空格等
		String regexs[] = { "\"", "\'", "<.*?>", "'", "<", ">", "nbsp",
				"[\\s\\r\\n]{1,}" };
		Pattern p = null;
		Matcher match = null;
		for (String regex : regexs) {
			p = Pattern.compile(regex, Pattern.DOTALL);
			match = p.matcher(about);
			if (match.find()) {
				about = match.replaceAll("");
			}
		}
		return about.trim();
		// return about.replaceAll("<.*?>", "");
	}

	public static boolean isValidUrl(String url) {
		// TODO Auto-generated method stub
		/*
		 * if(!url.contains("?")&&!url.startsWith("http")){ return false; }
		 */
		if(CommonUtil.isEmptyOrNull(url)){
			return false;

		}
		if (url.endsWith(".js") || url.endsWith(".css")) {
			return false;
		}
		return true;
	}

	public static List<String> convertToList(String[] strs) {
		List list = new ArrayList<String>();
		for (String str : strs) {
			list.add(str);
		}
		return list;
	}

	// remove file or remove directory
	public static void deleteFile(File file) {
		if (file.isFile()) {
			file.delete();
		}
		if (file.isDirectory()) {
			// first delete all the sub files
			for (File file1 : file.listFiles()) {
				deleteFile(file1);

			}
			// at last delete directory
			file.delete();
		}
	}

	// remove all the files related with svn
	public static void cleanSvnFolder(String directory) {
		File file = new File(directory);
		File[] files = file.listFiles();
		for (File tempFile : files) {
			if (tempFile.isDirectory()) {
				if (tempFile.getName().endsWith(".svn")) {
					CommonUtil.deleteFile(tempFile);
				} else {
					cleanSvnFolder(tempFile.getAbsolutePath() + "\\");
				}

			}

		}
	}

	// 将java文件中的所有特定字符串替换成指定的字符串
	@Deprecated
	public static void batchReplaceTextUnderFile(String directory)
			throws Exception, Exception {
		final String[] acceptFileNames = { ".java" };
		File file = new File(directory);
		File[] files = file.listFiles();
		for (File tempFile : files) {
			if (tempFile.isDirectory()) {
				batchReplaceTextUnderFile(tempFile.getAbsolutePath() + "\\");

			} else {
				if (tempFile.getName().endsWith(".java")) {
					String className = null;
					File file1 = tempFile;
					String classFullName = tempFile.getName();
					className = classFullName.substring(0,
							classFullName.indexOf("."));
					file1 = new File(directory + classFullName);
					String fileContent = IOUtils.translantByteStreamToString(
							IOUtils.translantStreamToByte(new FileInputStream(
									file1)), "utf-8");
					Pattern pattern = Pattern.compile(
							"public[\\s]{1,}enum[\\s]{1,}(.*?)[\\s]{1,}\\{",
							Pattern.CASE_INSENSITIVE);
					List<Pattern> patterns = new ArrayList<Pattern>();
					patterns.add(pattern);
					List<String> classNames = new ArrayList<String>();
					classNames = PatternUtils.getListStrByPattern(patterns,
							fileContent);
					for (String className1 : classNames) {
						String regex = "public [\\s]{0,}" + className1;

						fileContent = fileContent.replaceAll(regex, "private "
								+ className1);
					}

					file.delete();
					FileOutputStream ref = new FileOutputStream(directory
							+ classFullName);
					ref.write(fileContent.getBytes());
				}
			}
		}

	}



	public  static Object getObjectFromXml(InputStream in,Class cla) {

		Object obj=null;
		//URL resource=Thread.currentThread().getContextClassLoader().getResource(AppUtil.defaultCrawlerDateFilePath);//new ClassPathResource(AppUtil.defaultCrawlerDateFilePath);
//InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream(AppUtil.defaultCrawlerDateFilePath);
		
		JAXBContext jaxbContext;
		try {
			jaxbContext = JAXBContext.newInstance(cla);
			Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
		    obj= unmarshaller.unmarshal(in);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			mLog.error("reading Xml wrong!"+ExceptionUtil.getExceptionDetailsMessage(e)+"");
			throw new RuntimeException(e);
		} 
		
		return obj;

	}
	public static String native2Ascii(String str) {

		char[] chars = str.toCharArray();

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < chars.length; i++) {

			sb.append(char2Ascii(chars[i]));

		}

		return sb.toString();

	}


	private static String char2Ascii(char c) {

		if (c > 255) {

			StringBuilder sb = new StringBuilder();

			sb.append(Constants.PREFIX);

			int code = (c >> 8);

			String tmp = Integer.toHexString(code);

			if (tmp.length() == 1) {

				sb.append("0");

			}

			sb.append(tmp);

			code = (c & 0xFF);

			tmp = Integer.toHexString(code);

			if (tmp.length() == 1) {

				sb.append("0");

			}

			sb.append(tmp);

			return sb.toString();

		} else {

			return Character.toString(c);

		}

	}

	public static String getStrFromInputStream(InputStream inputStream,
			String defaultEncoding) {
		if (inputStream == null) {
			return null;
		}
		
		byte[] translantStreamToByte = IOUtils.translantStreamToByte(inputStream);
		//判断是否是utf-8编码
		final int usedBytesNumber=5000;
		if(CommonUtil.isEmptyOrNull(defaultEncoding)){
			if(CommonUtil.isValidUtf8(translantStreamToByte, usedBytesNumber)){
				defaultEncoding="utf-8";
			}
			else{
				defaultEncoding="GBK";
			}
			
		}
		
		
		return IOUtils.translantByteStreamToString(
				translantStreamToByte, defaultEncoding);

	}









public static String generateXmlForObject(Object obj, Class cla) {
		
		Writer outputWriter = new StringWriter(); 

		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(cla);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(obj, outputWriter);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		return outputWriter.toString();

	}
		
	public  static Object getObjectFromXml(StringReader in,Class cla) {

		Object obj=null;
		//URL resource=Thread.currentThread().getContextClassLoader().getResource(AppUtil.defaultCrawlerDateFilePath);//new ClassPathResource(AppUtil.defaultCrawlerDateFilePath);
	//	InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream(AppUtil.defaultCrawlerDateFilePath);
		
		JAXBContext jaxbContext;
		try {
			jaxbContext = JAXBContext.newInstance(cla);
			Unmarshaller unmarshaller=jaxbContext.createUnmarshaller();
		    obj= unmarshaller.unmarshal(in);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			mLog.error("reading Xml wrong!");
			throw new RuntimeException(e);
		} 
		
		return obj;

	}
	
/**
 * @param htmlContent
 * @return
 * 计算出一个html网页中内容在整个网页中的百分比
 */
public double getPercentageOfReallyCInHtml(String htmlContent){
	double  percentage = 0;
	int totalCount=0,contentCount=0;
	totalCount=htmlContent.length();
	htmlContent=htmlContent.replaceAll("<.*>", "");
	
	return percentage;
}






	/**
	 * @param data1
	 * @param data2
	 * @return 两个向里的相似度
	 * @用于比较两个向量的相似度（根据向量夹角余弦值来比较）
	 */
	public static double calculateSimilartity(List<Float> data1,
			List<Float> data2) {
		if (data1 == null || data2 == null || data1.size() != data2.size()) {
			throw new IllegalArgumentException();
		}
		double similartity = 0.00;
		Float value1 = 0.00f, value2 = 0.00f, value3 = 0.00f;
		for (int i = 0; i < data1.size(); i++) {
			value1 += data1.get(i).floatValue() * data2.get(i).floatValue();
			value2 += data1.get(i) * data1.get(i);
			value3 += data2.get(i) * data2.get(i);
		}
		similartity = value1 / Math.sqrt(value2 * value3);

		return similartity;
	}

	public static double calculateSimilartityByInteger(List<Integer> data1,
			List<Integer> data2) {
		if (data1 == null || data2 == null || data1.size() != data2.size()) {
			throw new IllegalArgumentException();
		}
		double similartity = 0.00;
		Float value1 = 0.00f, value2 = 0.00f, value3 = 0.00f;
		for (int i = 0; i < data1.size(); i++) {
			value1 += data1.get(i).floatValue() * data2.get(i).floatValue();
			value2 += data1.get(i) * data1.get(i);
			value3 += data2.get(i) * data2.get(i);
		}
		similartity = value1 / Math.sqrt(value2 * value3);

		return similartity;
	}
	/**
	 * @param sourceStr
	 * @return
	 * @计算一个文本中每个字符出现的次数组成的向量
	 */
	public static Map<String, Integer> getVectorofString(String sourceStr) {
		char[] chars = sourceStr.toCharArray();
		Map<String, Integer> charCountMap_str = new HashMap<String, Integer>();
		String temp = null;
		for (char ch : chars) {
			temp = String.valueOf(ch);
			if (charCountMap_str.get(temp) == null) {
				charCountMap_str.put(temp, 1);
			} else {
				charCountMap_str.put(temp, charCountMap_str.get(temp) + 1);

			}
		}

		return charCountMap_str;
	}

	/**
	 * @param str
	 *            ：与目标字符串相似性比较的字符串
	 * @param targetStr
	 *            ：目标字符串
	 * @return：得到两个带比较字符串的向量
	 */
	public static List<Integer>[] getVectorofString(String str, String targetStr) {
		List<Integer>[] lists = new ArrayList[2];
		if (str == null || targetStr == null) {
			throw new RuntimeException();
		}
		Map<String, Integer> charCountMap_str = new HashMap<String, Integer>();
		Map<String, Integer> charCountMap_targetStr = new HashMap<String, Integer>();

		char[] targetChars = targetStr.toCharArray();
		char[] chars = str.toCharArray();

		String temp = null;
		// get all chars across str and targetStr
		char[] allChars = new StringBuffer(str).append(targetStr).toString()
				.toCharArray();
		for (char ch : allChars) {
			temp = String.valueOf(ch);

			charCountMap_str.put(temp, 0);
			charCountMap_targetStr.put(temp, 0);

		}

		for (char ch : chars) {
			temp = String.valueOf(ch);

			charCountMap_str.put(temp, charCountMap_str.get(temp) + 1);

		}
		for (char ch : targetChars) {
			temp = String.valueOf(ch);

			charCountMap_targetStr.put(temp,
					charCountMap_targetStr.get(temp) + 1);

		}
		// 设置一些重要特征的权重
		if (charCountMap_targetStr.get("/") != null
				&& charCountMap_str.get("/") != null) {
			if (charCountMap_targetStr.get("/") != charCountMap_str.get("/")) {
				charCountMap_targetStr.put("/", 0);
				charCountMap_str.put("/", 100);
			}

		}
		lists[0] = new ArrayList<Integer>(charCountMap_str.values());
		lists[1] = new ArrayList<Integer>(charCountMap_targetStr.values());

		return lists;
	}

	public static String removeSpace(String str) {
		/*
		 * str=str.replaceAll("\r", ""); str=str.replaceAll("\n", "");
		 * str=str.replaceAll(" ", "");
		 */
		return str;
	}

	/**
	 * @param strs
	 *            ：要参与笛卡尔积运算的数组
	 * @return：一个包含所有可能组合数组的集合
	 */
	public static List<String[]> getDKL(List<String[]> strs) {

		if (strs.size() > 1) {
			String[] temp = new String[strs.get(0).length * strs.get(1).length];
			int index0 = 0;
			// 继续递归
			for (String str0 : strs.get(0)) {

				for (String str1 : strs.get(1)) {
					temp[index0] = str0 + "@" + str1;
					index0 += 1;

				}

			}

			strs.remove(0);
			strs.remove(0);

			strs.add(0, temp);
			return getDKL(strs);
		} else {
			List<String[]> returnStrs = new ArrayList<String[]>();
			String[] temp0 = null;
			for (String s : strs.get(0)) {

				temp0 = s.split("@");
				returnStrs.add(temp0);
			}

			return returnStrs;
		}
	}

	/**
	 * @param listStr
	 *            ：需要提取特征信息的一系列文本内容组成的集合(提取的特征可能是词元也可能是字符（对于中文）)
	 * @return：返回一个特征信息向量（比如：所有文档中频繁出现的字符的出现次数(求平均值)）可以抽象一个向量来表示
	 */
	public static Map<String, Double> getEigenvector(List<String> demoTexts) {
		DecimalFormat df2 = new DecimalFormat("###.00");

		// 所有样本文本信息中共同出现的字符的次数（字符为key,次数为value）
		Map<String, Double> vectorMap = new HashMap<String, Double>();
		// 务必确定集合中与demoTexts的顺序是一致的
		List<Map<String, Integer>> charNumberMaps = new ArrayList<Map<String, Integer>>();
		for (String str : demoTexts) {
			charNumberMaps.add(CommonUtil.getVectorofString(str));
		}
		boolean charIsAllOwned = false;
		float i = 0;
		// 随即取出一个样本文件中的charNumberMap
		Map<String, Integer> tempMap = charNumberMaps.get(0);
		mLog.info("抽取字符的文本内容为：" + demoTexts.get(0));
		Iterator<String> charIterator = tempMap.keySet().iterator();
		String ch;
		Double chCount = null;

		float chSumCount = 0, mapNumber = demoTexts.size();
		while (charIterator.hasNext()) {
			charIsAllOwned = false;
			chSumCount = 0;
			// 判断是否charIsAllOwned为true
			i = 0;
			ch = charIterator.next();
			for (Map<String, Integer> map : charNumberMaps) {
				if (map.keySet().contains(ch)) {
					i += 1;
					chSumCount += map.get(ch);

				}

				//

			}
			if (i / mapNumber > 0.8) {
				charIsAllOwned = true;
			}
			if (charIsAllOwned) {
				chCount = (double) (chSumCount / mapNumber);
				if (ch.equals("酒") || ch.equals("房")) {
					vectorMap.put(ch, 100.0);
				} else {
					vectorMap.put(ch, 1.0);
					// Double.valueOf(df2.format(chCount)));
				}

			}
		}

		return vectorMap;
	}
  
	public static String convertHtmlCharacter(String htmlStr) {
		String[] character = { "&","<", ">" }, updateStrs = { "&amp;","&lt;", "&gt;"
				 };

		int length = character.length;
		for (int i = 0; i < length; i++) {
			htmlStr = htmlStr.replaceAll(character[i], updateStrs[i]);

		}
		return htmlStr;
	}

	public static boolean isEmptyOrNull(Collection collection) {
		return collection == null || collection.size() == 0 ? true : false;
	}

	public static boolean isEmptyOrNull(String str) {
		return str == null || str.trim().length()==0 ? true : false;
	}

	public static boolean ifFieldHasGetAndSetMethod(Class classz, Field field) {

		Method[] methods = classz.getMethods();
		String getMethodName = null, setMethodName = null;
		int i = 0;
		getMethodName = "get" + CommonUtil.upFirstChar(field.getName());
		setMethodName = "set" + CommonUtil.upFirstChar(field.getName());
		for (Method method : methods) {

			if (getMethodName.equals(method.getName())
					|| setMethodName.equals(method.getName())) {
				i += 1;
			}
			if (i == 2) {
				return true;
			}
		}

		return false;
	}

	private static void getInterfaceOfCla(Class cla, List<Class<?>> interfaces) {
		Class<?>[] interfaces1 = cla.getInterfaces();
		if (interfaces1.length == 0) {
			return;
		} else {
			for (Class class1 : interfaces1) {
				interfaces.add(class1);
				getInterfaceOfCla(class1, interfaces);
			}

		}

	}

	/**
	 * @param clas
	 * @return get all the super interfaces of one class
	 */

	public static List<Class<?>> getALlInterfaces(Class clas) {
		List<Class<?>> interfaces = new ArrayList<Class<?>>();
		getInterfaceOfCla(clas, interfaces);

		return interfaces;
	}
public static Field getFieldByFieldName(Class classz,String fieldName){
	
	 List<Field> fields=CommonUtil.getAllDeclareFields(classz);
	 for(Field field0:fields){
		 if(field0.getName().equalsIgnoreCase(fieldName)){
			 return field0;
		 }
	 }
	return null;
	
}
	
	/**
	 * @param classz
	 * @return
	 *  获取所有一个类的所有熟属性包括父类(仅仅限于有get方法)
	 */
	public static List<Field> getAllDeclareFields(Class classz) {
		List<Field> fields = new ArrayList();
		Field[] fields1 = null;

		for (; classz != Object.class; classz = classz.getSuperclass()) {
			fields1 = classz.getDeclaredFields();

			for (Field field : fields1) {
				// 判断是否有get或者set方法
				if (CommonUtil.ifFieldHasGetAndSetMethod(classz, field)) {
					fields.add(field);

				}

			}

		}

		return fields;
	}

	/**
	 * @param resultList
	 * @throws Exception
	 */
	public static Object[] sort(Object[] results) throws Exception {
		// TODO Auto-generated method stub
		if (results == null) {
			throw new IllegalArgumentException();
		}
		try {
			Arrays.sort(results);
		} catch (Exception ex) {
			// do nothing
		}

		return results;
	}

	/**
	 * @param taskConfig
	 * @param class1
	 * @param path:存放该文件的目录路径
	 * @throws IOException 
	 */
	public static void generateXmlForObject(Object obj, Class cla, String path) throws IOException {
		// TODO Auto-generated method stub
		String tempDirectory = path;
		String fileName =System.currentTimeMillis()+".xml";         
		File file = new File(tempDirectory + fileName);
        if(!file.exists()){
        	file.createNewFile();
        }
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(cla);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(obj, file);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	public static void generateXmlForObjectA(Object obj, Class cla, String path) throws IOException {
		// TODO Auto-generated method stub
	
         
		File file = new File(path);
        if(!file.exists()){
        	file.createNewFile();
        }
        else{
        	file.delete();
        }
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(cla);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(obj, file);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	/**
	 * @param type
	 * @return 判断是否是用户自定义的实体类（此种类型的类往往需要用户操作比如：浏览内容以及编辑里面的内容）
	 */
	public static boolean isCustomerObjType(Class type) {
		if (type.isPrimitive()) {
			return false;
		}

		boolean b1 = isCollection(type) || type.isAssignableFrom(String.class)
				|| type.isAssignableFrom(Date.class);
		boolean b2 = type.isAssignableFrom(Double.class)
				|| type.isAssignableFrom(Character.class)
				|| type.isAssignableFrom(Long.class)
				|| type.isAssignableFrom(Float.class)
				|| type.isAssignableFrom(Integer.class) || type.isEnum();

		if (b1 || b2) {
			return false;
		}
		return true;
	}

	/**
	 * 判断某个属性是否是用户自定义的对象类型
	 * 
	 * @return
	 */
	public static boolean isCustomerObjType(Field property) {
		Class<?> type = property.getType();
		if (type.isPrimitive()) {
			return false;
		}

		boolean b1 = isCollection(type) || type.isAssignableFrom(String.class)
				|| type.isAssignableFrom(Date.class);
		boolean b2 = type.isAssignableFrom(Character.class)
				|| type.isAssignableFrom(Long.class)
				|| type.isAssignableFrom(Float.class)
				|| type.isAssignableFrom(Integer.class) || type.isEnum();

		if (b1 || b2) {
			return false;
		}
		return true;

	}

	public static boolean isCollection(Class<?> type) {
		if (type.getInterfaces().length == 0) {
			return false;
		}

		/*
		 * if(type.getInterfaces()[0].isAssignableFrom(Collection.class)){
		 * return true; }
		 */
		List<Class<?>> interfaces = CommonUtil.getALlInterfaces(type);
		if (interfaces.contains(Collection.class)) {
			return true;
		}
		return false;

	}

	/**
	 * @param pixel
	 * @return 从像素值获取r,g,b
	 */
	public static int[] getRGBFromPixel(int pixel) {
		int[] colorValues = new int[3];
		colorValues[0] = (pixel & 0Xff0000) >> 16;
		colorValues[1] = (pixel & 0Xff00) >> 8;
		colorValues[2] = (pixel & 0Xff);
		return colorValues;

	}

	/**
	 * @param red
	 * @param green
	 * @param blue
	 * @return 从r,g,b计算像素值
	 */
	public static int getPixelFromRGB(int red, int green, int blue) {
		return (red << 16) + (green << 8) + (blue);

	}

	public static double getFiguresSimilartity() {
		double similartity = 0.00;
		return similartity;
	}
	// 對一個圖像的像素進行縮放以及平移
	
	//不同类别对象和字符串之间的转换
	
	/**
	 * @param targetCla
	 * @param value
	 * @return
	 * 主要用于将表格中编辑过的单元格中的字符串对象转换成其原始对象（单元格一经编辑此单元格中保存的对象类型也就发生了变化，不起之前类型如何，都会变成字符串类型
	 * 因此在保存的时候需要进行转换）
	 */
	public static   Object   objectConvert(Class targetCla,Object value){
		if(value==null){
			return null;
			
		}
		mLog.debug("此次转换目标类为："+targetCla.getName()+";要转换的值的类型为："+value.getClass().getName());
		Object object=value;
		
		if(targetCla.isAssignableFrom(String.class)&&value.getClass().isAssignableFrom(String.class)){
	     object=value;
	}
	if(Double.class.isAssignableFrom(targetCla)&&value.getClass().isAssignableFrom(String.class)){
			object=Double.parseDouble((String)value);
		}
	
	if(Integer.class.isAssignableFrom(targetCla)&&value.getClass().isAssignableFrom(String.class)){
			object=Integer.valueOf((String)value);
	}
	//增加对与枚举的支持
	if(targetCla.isEnum()){
		object=object.toString();
	}
	if(Long.class.isAssignableFrom(targetCla)&&value.getClass().isAssignableFrom(String.class)){
		object=Long.valueOf((String)value);
}
	if(Boolean.class.isAssignableFrom(targetCla)&&value.getClass().isAssignableFrom(String.class)){
		object=Boolean.valueOf((String)value);
}
		return object;
		
	}
	public String detectorEncodingFromBytes(byte[] bytes){
		String encodingName=null;
         CharsetDetector detector = new CharsetDetector();
         detector.setText(bytes);
         CharsetMatch[] matches = detector.detectAll();
         matches[0].getConfidence();
         matches[0].getName();

		return encodingName;
	}
	public static List<String> generateUrlsByPaginationRule(
			PaginationRule paginationRule) {
		if (paginationRule == null
				|| paginationRule.getPaginationTemplate() == null) {
			return null;
	
		}
		List<String> urls = new ArrayList<String>();
		String paginationTemplate = paginationRule.getPaginationTemplate();
		List<UrlParameter> urlParameters = paginationRule.getUrlParameters();
		Collections.sort(urlParameters, new Comparator<UrlParameter>() {
	
			public int compare(UrlParameter o1, UrlParameter o2) {
				// TODO Auto-generated method stub
				if (o1.getParameterIndex() > o2.getParameterIndex()) {
					return 1;
				}
				return -1;
			}
		});
	
		String[] strs = new String[urlParameters.size()];
		List<String[]> strses = new ArrayList<String[]>();
		// 每个urlParameter对应的值得数组
		List<String[]> strses1 = new ArrayList<String[]>();
		String[] temp = null;
	
		for (UrlParameter urlParameter : urlParameters) {
			if (urlParameter.getParameterType().equals("String")) {
				temp = urlParameter.getParameterValue().split(Constants.stringSplitSymbol);
			}
			if (urlParameter.getParameterType().equals("Integer")) {
				String maxpageNumber = urlParameter.getParameterValue();
				// 根据分页数差生一个页数数组
			    //simple by pageNumber
			    if(urlParameter.getBegainPagNumber()==null&&urlParameter.getPagNumberSpace()==null){
			    	temp = new String[Integer.valueOf(maxpageNumber)];
			    	for (int i = 1; i <= Integer.valueOf(maxpageNumber); i++) {
						temp[i - 1] = String.valueOf(i);
					}
			    }
			    //by recoredNumber
			    else{
			    	temp = new String[Integer.valueOf(maxpageNumber)];
			    	for (int i = 1; i <= Integer.valueOf(maxpageNumber); i++) {
						temp[i - 1] = String.valueOf(urlParameter.getBegainPagNumber()+(i-1)*urlParameter.getPagNumberSpace());
					}
			    }
				
			}
			for(int i=0;i<temp.length;i++){
				temp[i]=HtmlUtil.encoderUrl(temp[i]);
			}
			strses1.add(temp);
	
		}
		strses = getDKL(strses1);
		String url =null;
		for (String[] stres : strses) {
			 url = replaceByIndex(paginationTemplate, "\\{\\}",stres);
	         urls.add(url);
		}
		return urls;
	}

	public static <K> List<List<K>> splitKs(Collection<K> ks,int blockSize){
		if(isEmptyOrNull(ks)){
			return null;
		}
		if(blockSize<=0){
			throw new IllegalArgumentException("请设置blockSize！");
		}
		List<List<K>> urlsGroup=new ArrayList<List<K>>();
		int totalUrlSize=ks.size();
		List<K> tempUrls=null;
		int groupCount=totalUrlSize/blockSize;
		int lastGroupElementCount=totalUrlSize%blockSize;
		if(groupCount==0){
			groupCount+=1;
		}
		K o=null;
		for(int i=0;i<groupCount;i++){
			tempUrls=new ArrayList<K>();
			for(int index=i*blockSize;index<(i+1)*blockSize;index++){
				//当groupCount==0的时候避免指针溢出
				if(index>=totalUrlSize){
					break;
				}
				o = (K) ks.toArray()[index];
				tempUrls.add(o);
			}
			urlsGroup.add(tempUrls);
			
		}
		//检测是否剩余一组小于blockSize,如果小于blockSiza则将剩余的最后一组url加入到之前urlsGroup的最后一个分组集合中
		//改为新建一个组
		if(lastGroupElementCount!=0&&groupCount>1){
			urlsGroup.add((List<K>) new ArrayList<>());
			for(int index=groupCount*blockSize;index<totalUrlSize;index++){
				//当groupCount==0的时候避免指针溢出

				if(index>=totalUrlSize){
					break;
				}
				
				o = (K) ks.toArray()[index];
				urlsGroup.get((groupCount)).add(o);
			}
		}
		return urlsGroup; 
		
	}
	public static String LinkStringWithSpecialSymbol(Collection<String> strCollection,String specialSymbol){
		if(CommonUtil.isEmptyOrNull(strCollection)||CommonUtil.isEmptyOrNull(specialSymbol)){
			throw new IllegalArgumentException();
		}
		StringBuffer str=new StringBuffer();
		for(Object tempStr:strCollection.toArray()){
			
			str.append(tempStr).append(specialSymbol);
			
		}
		
		return str.toString().substring(0, str.toString().lastIndexOf(specialSymbol));
	}
	/**
	 * @param superClass
	 * @return 一个超类的运行时子类
	 */
	public static Class getSubClassOfSuperClass(Class superClass){
		Class subClass=null;
		
			subClass=superClass.getClass();

	
		return subClass;
	}
	/**
	 * @param b
	 * @param aMaxCounton
	 * @return
	 * 用于判断一个byte数组是否是utf-8编码
	 */
	public static boolean isValidUtf8(byte[] b,int aMaxCount){

	       int lLen=b.length,lCharCount=0;

	       for(int i=0;i<lLen && lCharCount<aMaxCount;++lCharCount){

	              byte lByte=b[i++];//to fast operation, ++ now, ready for the following for(;;)

	              if(lByte>=0) continue;//>=0 is normal ascii

	              if(lByte<(byte)0xc0 || lByte>(byte)0xfd) return false;

	              int lCount=lByte>(byte)0xfc?5:lByte>(byte)0xf8?4

	                     :lByte>(byte)0xf0?3:lByte>(byte)0xe0?2:1;

	              if(i+lCount>lLen) return false;

	              for(int j=0;j<lCount;++j,++i) if(b[i]>=(byte)0xc0) return false;

	       }

	       return true;

	}
	/**
	 * @param arrays
	 * @return null if arrays in null or legth=0
	 * 用于将数组转换成一个arrayList
	 */
	public static  List convertArrayToList(Object[] arrays){
		if(arrays==null||arrays.length==0){
			return null;
		}
		List list=new ArrayList();
		for(Object obj:arrays){
			list.add(obj);
		}
		return list;
	}
	/**
	 * @param cla
	 * @return
	 * 获取jar所在目录路径
	 */
	public static String getJarParentPath(Class cla){
		String jarPath=null;
		jarPath = cla.getProtectionDomain().getCodeSource().getLocation()  
	                .getFile();  
	        try {  
	        	jarPath = java.net.URLDecoder.decode(jarPath, "UTF-8");  
	        } catch (java.io.UnsupportedEncodingException ex) {  
	           mLog.info(ExceptionUtil.getExceptionDetailsMessage(ex));
	        }  
	        java.io.File jarFile = new java.io.File(jarPath);  
	        
	        java.io.File parent = jarFile.getParentFile();  
	        if (parent != null) {  
	        	jarPath = parent.getAbsolutePath();  
	        }  
		return jarPath;
	}
	/**
	 * @param keyWordLevel1:京东商品查询关键字
	 * @param keyWordLevel2:商品描述中的关键字
	 * @return
	 */
	public static int getPageNumberByKeyword(String keyWordLevel1,String keyWordLevel2){
		int pageNumber=-1;

		final StringBuffer searchUrl=new StringBuffer();
		//http://search.360buy.com/s.php?keyword=%E5%9B%9B%E4%BB%B6%E5%A5%97&enc=utf-8&area=1&psort=&page=7&qr=&qrst=UNEXPAND&et=&sttr=
		searchUrl.append("http://search.360buy.com/s.php?keyword=");
		searchUrl.append(keyWordLevel1);
		searchUrl.append("&enc=utf-8&area=2&psort=&page={}&qr=&qrst=UNEXPAND&et=&sttr=");
	    String queryUrl= HtmlUtil.decodeUrl(searchUrl.toString());
	    int maxPageNumber=2000;
	    String currentQueryUrl=null;
	    String currentHtmlContent=null;
	    String currentRegex="<div[\\s]{0,}class=\"p-name\">([\\s\\S\\r\\n]{0,}?)</div>";
	    List<String> matchGoodName=null;
	    String lastPageContent=null;
	    //匹配各个关键词（之间必须以空格隔开）
	    String[] keywords=keyWordLevel2.split(" ");
	    boolean notMatchEveryKeyWords=false;
	    for(int i=1;i<maxPageNumber;i++){
	    	currentQueryUrl=queryUrl.replace("{}", String.valueOf(i));
	    	try {
				currentHtmlContent=CommonUtil.getHtmlContent(null, false, currentQueryUrl);
				if(lastPageContent!=null){
					if(currentHtmlContent.trim().length()==lastPageContent.trim().length()){
						return -1;
					}
				}
				matchGoodName=PatternUtils.getListStrByRegex(currentHtmlContent, currentRegex);
				if(matchGoodName!=null){
					for(String goodName:matchGoodName){
						notMatchEveryKeyWords=false;
						for(String perKeyword:keywords){
							if(!goodName.contains(perKeyword.trim())){
								notMatchEveryKeyWords=true;
								break;
							}	
						}
						if(!notMatchEveryKeyWords){
							return i;
						
						}
					}
					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				return -1;
			}
	    	lastPageContent=currentHtmlContent;
	    }
		return pageNumber;
	}
	/**
	 * 根据淘宝中的关键字来查询商品并且获取对应商品的卖家店铺名称
	 */
	public static String getSellerNameOfTaobaoItem(String keyword,String resultSavedPath){
   
	//s=0,40,80
	final StringBuffer searchUrl=new StringBuffer();
	//http://search.360buy.com/s.php?keyword=%E5%9B%9B%E4%BB%B6%E5%A5%97&enc=utf-8&area=1&psort=&page=7&qr=&qrst=UNEXPAND&et=&sttr=
	searchUrl.append("http://s.taobao.com/search?q=");
	searchUrl.append(HtmlUtil.encoderUrl(keyword));
	searchUrl.append("&bcoffset=6&newpre=null&s={}#J_FilterTabBar");
	String maxPageNumberPattern="\"page-info\">(.*?)</span>";
String	maxPageNumberPattern_32="page-info>(.*?)</span>";
	String firstPageUrl=searchUrl.toString().replace("{}", "0");
    mLog.info(""+firstPageUrl+"");
	String maxPageNumberStr = null;
	try {
		String htmlContent = CommonUtil.getHtmlContent(firstPageUrl, true);
		mLog.debug(htmlContent);

		String strByRegex = PatternUtils.getStrByRegex(htmlContent, maxPageNumberPattern);
		if(CommonUtil.isEmptyOrNull(strByRegex)){
			strByRegex = PatternUtils.getStrByRegex(htmlContent, maxPageNumberPattern_32);
		}
		maxPageNumberStr = strByRegex.substring(strByRegex.lastIndexOf("/")+1);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    //int maxPageNumber=Integer.valueOf(maxPageNumberStr);
	String queryUrl=searchUrl.toString();
    PaginationRule paginationRule = new PaginationRule();
    paginationRule.setPaginationTemplate(queryUrl);
    UrlParameter urlParameter=new UrlParameter();
    urlParameter.setBegainPagNumber(0);
    urlParameter.setPagNumberSpace(40);
    urlParameter.setParameterType("Integer");
    urlParameter.setParameterValue(maxPageNumberStr);
    paginationRule.getUrlParameters().add(urlParameter);
	List<String> urls=CommonUtil.generateUrlsByPaginationRule(paginationRule);
	
	List<String> sellerNames=new ArrayList<String>();
	String sellerNamePattern="shopinfo[\\s\\S\\r\\n]{0,}?>(.*?)<";
	List<String> strss=null;
	for(String urlT:urls){
	
		try{
			//sellerNames.addAll(PatternUtils.getListStrByRegex(CommonUtil.getHtmlContent(urlT, true), sellerNamePattern));
			String htmlContent = CommonUtil.getHtmlContent(urlT, true);
		
			strss=PatternUtils.getListStrByRegex(htmlContent, sellerNamePattern);
			for(String str:strss){
				if(!sellerNames.contains(str)){
					sellerNames.add(str);
				}
			}
		}catch(Exception e){
			
		}
	}
	//produce execl
	String fileName=FileUtil.gernerateExcelFromList(sellerNames, resultSavedPath);
	return fileName;
	}
	//
	
	private static void quickSort(int[] nums, int i, int j) { 
        int left = i; 
        int right =j; 
        int temp = 0; 
        boolean r_or_l = true; 
        if(left>=right){ 
            return; 
        } 
        while(left<right){ 
            if(nums[left]>nums[right]){ 
                temp = nums[left]; 
                nums[left] = nums[right]; 
                nums[right] = temp; 
                r_or_l = r_or_l?false:true; 
            } 
            if(r_or_l){ 
                right--; 
            } else { 
                left++; 
            } 
        }     
        left-=1; 
        right+=1; 
        //System.out.println(right+" "+left); 

        quickSort(nums, 0, left); 
        quickSort(nums, right, j); 
    } 
	public static List<String> makeUrlsByPaginationTemplate(String paginationTemplate,int begainPagNumber,int pageNumberSpace,int paraValue){
		if(!paginationTemplate.contains("{}")){
			throw new IllegalArgumentException("参数有误");
		}
		PaginationRule paginationRule = new PaginationRule();
	    paginationRule.setPaginationTemplate(paginationTemplate);
	    UrlParameter urlParameter=new UrlParameter();
	    urlParameter.setBegainPagNumber(begainPagNumber);
	    urlParameter.setPagNumberSpace(pageNumberSpace);
	    urlParameter.setParameterType("Integer");
	    urlParameter.setParameterValue(String.valueOf(paraValue));
	    paginationRule.getUrlParameters().add(urlParameter);
		List<String> urls=CommonUtil.generateUrlsByPaginationRule(paginationRule);
		return urls;
	}
	public static Object instanceClassByConstructor(String className,Class[] pType,Object[] paras){
		Object result=null;
		Class cla=null;
		try {
			cla = Class.forName(className);
		
        Constructor ctor = cla.getConstructor(pType);  

    

         result = ctor.newInstance(paras);  
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return result;
	}
	public static void quickSort1(int[] nums,int left,int right){
		if(left>=right){
			return ;
		}
		int temp=0;
		int key=nums[left];
		int index=-1;
		while(left<right){
			left++;
			if(nums[left]<key){
				nums[left-1]=nums[left];
				nums[left]=key;
				index=left;
			}

if(nums[right]<key){
	temp=nums[right];
	nums[right]=key;
	nums[left]=temp;
	index=right;
}
right--;

		}
		quickSort1(nums, 0, index-1);
		quickSort1(nums, index+1, right);
		
	}
}
